import { prisma } from '@/lib/prisma';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { notFound } from 'next/navigation';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/auth.config';
import { CommentSection } from '@/app/components/CommentSection';
import { Trip, Activity, User } from '@prisma/client';
import { ShareTripButton } from '@/app/components/ShareTripButton';

type CommentWithUser = {
  id: string;
  content: string;
  tripId: string;
  userId: string;
  createdAt: Date;
  updatedAt: Date;
  user: {
    id: string;
    name: string | null;
  };
};

type TripWithDetails = Trip & {
  activities: Activity[];
  user: {
    name: string | null;
  };
  savedBy: User[];
  comments: CommentWithUser[];
  _count: {
    activities: number;
  };
};

async function getTrip(id: string): Promise<TripWithDetails> {
  const trip = await prisma.trip.findUnique({
    where: { id },
    include: {
      activities: {
        orderBy: { date: 'asc' }
      },
      user: {
        select: { name: true }
      },
      savedBy: true,
      comments: {
        include: {
          user: {
            select: { id: true, name: true }
          }
        },
        orderBy: { createdAt: 'desc' }
      },
      _count: {
        select: { activities: true }
      }
    }
  });

  if (!trip) notFound();
  return trip as TripWithDetails;
}

export default async function TripDetailPage({
  params
}: {
  params: { id: string }
}) {
  const trip = await getTrip(params.id);
  const session = await getServerSession(authOptions);
  const isSaved = trip.savedBy.some(user => user.id === session?.user?.id);

  return (
    <div className="max-w-4xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
        {/* 行程头部信息 */}
        <div className="p-6 border-b border-gray-200">
          <div className="flex justify-between items-start">
            <div>
              <h1 className="text-2xl font-bold text-gray-900 mb-2">
                {trip.title}
              </h1>
              {trip.description && (
                <p className="text-gray-600 mb-4">{trip.description}</p>
              )}
              <div className="flex items-center text-gray-500 text-sm">
                <span className="mr-4">
                  {format(trip.startDate, 'yyyy年MM月dd日', { locale: zhCN })} - {format(trip.endDate, 'yyyy年MM月dd日', { locale: zhCN })}
                </span>
                <span>共 {trip._count.activities} 个活动</span>
              </div>
            </div>
            {trip.imageUrl && (
              <img
                src={trip.imageUrl}
                alt={trip.title}
                className="w-32 h-32 object-cover rounded-lg"
              />
            )}
          </div>
        </div>

        {/* 行程活动列表 */}
        <div className="p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">行程安排</h2>
          <div className="space-y-6">
            {trip.activities.map((activity, index) => (
              <div key={activity.id} className="relative pl-8">
                {/* 时间线 */}
                {index !== trip.activities.length - 1 && (
                  <div className="absolute left-3 top-3 bottom-0 w-px bg-gray-200" />
                )}
                <div className="absolute left-0 top-1.5 w-6 h-6 rounded-full bg-blue-100 border-2 border-blue-500 flex items-center justify-center">
                  <span className="text-xs font-medium text-blue-500">
                    {index + 1}
                  </span>
                </div>
                
                <div className="bg-gray-50 rounded-lg p-4">
                  <h3 className="font-medium text-gray-900">{activity.title}</h3>
                  <p className="text-sm text-gray-500 mt-1">
                    {format(activity.date, 'MM月dd日 HH:mm', { locale: zhCN })}
                  </p>
                  {activity.description && (
                    <p className="text-gray-600 mt-2">{activity.description}</p>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* 底部信息 */}
        <div className="px-6 py-4 bg-gray-50 border-t border-gray-200">
          <div className="flex justify-between items-center">
            <div className="text-sm text-gray-500">
              <span>
                创建于 {format(trip.createdAt, 'yyyy年MM月dd日', { locale: zhCN })}
              </span>
              {trip.user.name && <span className="ml-4">创建者: {trip.user.name}</span>}
            </div>
            <ShareTripButton tripId={trip.id} />
          </div>
        </div>
      </div>

      {/* 添加评论部分 */}
      <CommentSection 
        tripId={trip.id}
        initialComments={trip.comments}
      />
    </div>
  );
} 